<template>
  <view class="dashed-box">
    <!-- 动态生成签名栏 -->
    <view v-if="showSignList" v-for="(item, index) in signList" :key="index" class="custom-title gap-4 items-center">
      <text> {{ item.signaturePosition }}签名: </text>
      <view class="flex-1 justify-center flex border-b">
        <signInput
          bgColor="#ffffff"
          :ref="`sign_${index}`"
          :action="action"
          :canvasId="canvasKey + index"
          :canvasIds="canvasKey + 'sign' + index"
          @signToUrl="(e) => handleSign(e, index)"
          :outSignHeight="outSignHeight"
          :outSignWidth="outSignWidth"
          :initialImage="item.signature || ''"
          @deleteImg="handleDeleteImg(index)"
        ></signInput>
      </view>
      
    </view>

    <!-- 添加更多 -->
    <view v-if="showAdd" class="dashed-box3" @click="showRolePicker">
      <text style="font-size: 20rpx; font-weight: bold"
        >+点此添加更多签字栏</text>
    </view>

    <!-- 日期 -->
    <view class="custom-dateText" @click="openDatePicker" v-if="showDate">
      <text class="custom-text3">{{ formatterDate.year || '编辑' }}</text>年
			<text class="custom-text3">{{ formatterDate.month || '编辑' }}</text>月
			<text class="custom-text3">{{ formatterDate.day || '编辑' }}</text>日
    </view>

    <!-- 添加日期选择弹窗 -->
    <uni-popup ref="datePopup" type="dialog">
      <uni-popup-dialog
        mode="base"
        title="选择日期"
        @confirm="handleConfirmDate"
        @close="handleCloseDate"
      >
        <uni-datetime-picker :value="signDate" type="date" @change="handleDateChange" />
      </uni-popup-dialog>
    </uni-popup>

    <!-- 角色选择弹窗 -->
    <uni-popup ref="rolePopup" :type="rolePopupPosition">
      <slot>
        <uni-popup-dialog
          mode="base"
          title="选择角色"
          @confirm="confirmRole"
          @close="closeRolePopup"
        >
          <picker
            :range="checkGroupPositionList"
            range-key="label"
            @change="handleRoleChange"
          >
            <view class="picker"
              >当前选择：{{ selectPosition }}</view
            >
          </picker>
        </uni-popup-dialog>
      </slot>
    </uni-popup>
  </view>
</template>

<script>
import signInput from "@/components/am-sign-input/am-sign-input.vue";
import { uploadUrl } from "../../config";
import { transformDate, formatterTime } from '@/utils/common';
import { getMedicalDict } from '@/api/order'
export default {
  props: {
    // 初始签名列表
    signList: {
      type: Array,
      default: () => [],
    }, // 新增控制显隐的 prop
    showAdd: {
      type: Boolean,
      default: true, // 默认显示
    },
    showDate: {
      type: Boolean,
      default: true,
    },
    rolePopupPosition: {
      type: String,
      default: 'dialog'
    },
    showSignList: {
      type: Boolean,
      default: true
    },
    date: String,
    canvasKey: {
      type: String,
      requried: true
    },
    outSignHeight: {
      type: Number,
      default: 240
    },
    outSignWidth: {
      type: Number,
      default: 540
    }
  },
  components: {
    signInput,
  },
  data() {
    return {
      action: uploadUrl,
      signDate: '',
      checkGroupPositionList: [],
      selectIndex: null
    };
  },
  watch: {
    date(val){
      this.signDate = val;
    }
  },
  computed: {
    formatterDate(){
      return transformDate(this.date);
    },
    selectPosition() {
      return this.checkGroupPositionList[this.selectIndex]?.label
    }
  },
  created(){
    if(this.showSignList && !this.canvasKey) throw new Error('canvasKey is required')
    getMedicalDict('checkGroup_position').then(res => {
      this.checkGroupPositionList = res.data
    });
  },
  methods: {
    // 关闭角色选择弹窗
    closeRolePopup() {
      this.selectIndex = null;
      this.$refs.rolePopup.close();
    },

    // 处理角色选择变化
    handleRoleChange(e) {
      this.selectIndex = e.detail.value;
    },
    showRolePicker() {
      this.$refs.rolePopup.open();
    },
    confirmRole() {
      try{
        this.$emit('update:signList', [
          ...this.signList,
          {
            signaturePosition: this.checkGroupPositionList[this.selectIndex]?.label, 
            signature: ''
          }
        ])
        return this.closeRolePopup();
      }catch(err){
        uni.showToast({
          content: err
        })
      }
      
    },
    handleSign(e, index) {
      if (e.error_code && e.error_code === "201") {
        uni.showToast({
          title: e.msg,
          icon: "none",
        });
        return;
      }
      const response = JSON.parse(e.data);
      this.$set(this.signList, index, {
        ...this.signList[index],
        signature: response.data,
      });
      this.$emit("update:signList", this.signList);
    },
    openDatePicker() {
      this.signDate = formatterTime(this.date);
      this.$refs.datePopup.open();
    }, 
    // 弹窗关闭
    handleCloseDate() {
      this.$refs.datePopup.close();
    },
    // 日期变化暂存
    handleDateChange(e) {
      this.signDate = e;
    },
    handleConfirmDate() {
      this.$emit('date-change', this.signDate);
      return this.handleCloseDate();
    },
    handleDeleteImg(index){
       this.$set(this.signList, index, {
        ...this.signList[index],
        signature: null,
      });
      this.$emit("update:signList", this.signList);
    }
  },
};
</script>
<style lang="scss" scoped>
/* 保持原有样式不变 */
/* 虚线容器 */
.dashed-box {
  width: 100%;
  padding: 12rpx;
  border-radius: 10rpx;
  background: #fff;
  position: relative;

  & + .dashed-box {
    margin-top: 28rpx;
  }

  .custom-title {
    display: flex;

    margin-bottom: 10px;
    /* 保持原有下边距 */

    text {
      margin-right: 20px;
      color: black;
      font-size: 17px;
      font-weight: bold;
    }
  }

  .custom-dateText {
    display: flex;
    margin: 20px;
    justify-content: flex-end;
    /* 子元素居左 */
  }

  .custom-text3 {
    border-bottom: 1px solid #000;
    padding-bottom: 2px;
    padding-left: 10px;
    color: #0055ff;
    font-size: 16px;

    font-weight: bold;
    padding-right: 10px;
    margin-left: 4px;
    margin-right: 4px;
  }
}

/* 虚线容器 */
.dashed-box3 {
  width: 100%;
  border: 2rpx dashed #0055ff;
  border-radius: 10rpx;
  background: #e5ecff;
  height: 120px;
  /* 设置为flex布局 */
  display: flex;
  /* 水平居中 */
  justify-content: center;
  /* 垂直居中 */
  align-items: center;
}

.role-picker {
  background: #fff;
  height: 300rpx;
}

.picker-item {
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
}
</style>
